<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/*
 * @name Departments
 * @type Controller
 * @autor StackFeed LLC
 * @version 2.4
 *
 * @description - Departments controller is used for creating, editing
 * viewing, deactivating, activating, or uplading files to a department.
 */
class Departments extends CI_Controller 
{
	/*
	 * Default constructor.
	 */
	function __construct()
	{
		parent::__construct();
        $this->load->library('ion_auth');
        $this->load->library('form_validation');
        $this->load->library('session');
        $this->load->library('pagination');
        $this->load->database();
        $this->lang->load('auth');
        $this->lang->load('admin_estate');
        $this->load->helper('language');
        $this->load->model('admin_estate_model');
        $this->load->model('company_model');
        $this->load->model('Departments_model');
	}
	
	/*
	 * Index.
	 */
	function index()
	{
		$company_id  = 1;
		$departments = $this->Departments_model->get_company_departments($company_id);
		
		$data = array('departments' => $departments);
		
		$this->data['ptitle'] = 'Departments';
		$data['success_message'] = '';
		$data['message'] = '';
		$this->session->set_userdata('page', 12);
		$this->tmadmin->tmView('departments/index', $data);
	}
	
	/*
	 * Viewing a single department. You can view the open, closed, projects
	 * users, and attachments to the department.
	 * 
	 * @department_id The department that we are trying to view.
	 */
	function view($department_id = null)
	{
		// Verify they have typed in a department.
		if(!$department_id)
			redirect('departments');
		
		// Get company id to verify the department.
		$company_id = 1;
		
		// Verify the department belongs to the company.
		if(!$this->company_model->is_valid_department($company_id, $department_id))
			redirect('departments');
		
		// Get department information.
		$department       = $this->Departments_model->get_individual_department($company_id, $department_id);
		$projects         = $this->Departments_model->get_department_projects($company_id, $department_id);
		$open_tickets     = $this->Departments_model->get_open_tickets($company_id, $department_id);
		$closed_tickets   = $this->Departments_model->get_closed_tickets($company_id, $department_id);
		$users 		      = $this->Departments_model->get_users($company_id, $department_id);
		$attachments      = $this->Departments_model->get_department_attachments($company_id, $department_id);
		$file_comments 	  = $this->Departments_model->get_file_comments($company_id, $department_id, $attachments);
		$dept_projects    = $this->Departments_model->get_department_projects($company_id, $department_id);
		$dept_users	      = $this->Departments_model->get_users($company_id, $department_id);
		$company_users    = $this->company_model->get_all_users_include_inactive($company_id);
		$company_projects = $this->company_model->get_all_projects_include_inactive($company_id);
		
		// Build data array.
		$data = array('department'       => $department,
					  'projects'         => $projects,
					  'open_tickets'     => $open_tickets,
					  'closed_tickets'   => $closed_tickets,
					  'users'		     => $users,
					  'attachments'	     => $attachments,
					  'dept_projects'    => $dept_projects,
					  'dept_users'	     => $dept_users,
					  'company_users'    => $company_users,
					  'company_projects' => $company_projects,
					  'file_comments'	 => $file_comments);
		
		// Load views.
		$this->data['ptitle'] = 'View Departments';
		$this->tmadmin->tmView('departments/view', $data);
	}
	
	/*
	 * Uploading a file. I do not recommend uploading to a directory on
	 * your server. But not everyone will have access to cookieless domains
	 * such as Amazon S3.
	 * 
	 * @department_id The department we are going to upload a file to.
	 */
	function upload($department_id = null)
	{
		// Verify they have typed in a department.
		if(!$department_id)
			redirect('departments');
	
		$company_id = 1;
		$user_id    = $this->session->userdata('user_id');
	
		// Verify the department belongs to the company.
		if(!$this->Company_model->is_valid_department($company_id, $department_id))
			redirect('departments');
	
		// Get all of the POST data and filter what needs filtered.
		$real_name     = $this->db->escape($_FILES['file']['name']);
		$hash_name     = $this->functions->hash_filename($_FILES['file']['name']);
		$extension     = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
		$hash_name     = $hash_name.'.'.$extension;
		$type          = $this->db->escape($_FILES['file']['type']);
		$size_kb       = $_FILES['file']['size'] / 1024;
		$size_mb       = $_FILES['file']['size'] / 1048576;
		$description   = $this->db->escape($_POST['description']);
	
		// Verify no errors in file.
		if($_FILES['file']['error'] > 0)
		{
			$data['error'] = 'Please select a file to upload.';
			$this->session->set_flashdata($data);
	
			redirect("departments/view/{$department_id}");
		}
	
		// Submit file data to database.
		if(!$this->Departments_model->upload($company_id, $department_id, $user_id, $real_name, $hash_name, $type, $size_kb, $size_mb, $description))
		{
			$data['error'] = 'There was an error processing.';
			$this->session->set_flashdata($data);
	
			redirect("departments/view/{$department_id}");
		}
	
		// Put on server.
		move_uploaded_file($_FILES['file']['tmp_name'], getcwd().DIRECTORY_SEPARATOR.'assets'.DIRECTORY_SEPARATOR.'uploads'.DIRECTORY_SEPARATOR.'departments'.DIRECTORY_SEPARATOR.$hash_name);
	
		redirect("departments/view/{$department_id}");
	}
	
	/*
	 * Removing a file will remove it from the database as
	 * well as delete it from the server.
	 * 
	 * @department_id The department ID where the file is stored.
	 * @file_id       The file ID that is going to be removed.
	 */
	function remove($department_id, $file_id)
	{
		// Verify they have typed in a department and file.
		if(!$department_id && !$file_id)
			redirect('departments');
	
		$company_id = 1;
	
		// Verify the file belongs to the company.
		if(!$this->Company_model->is_valid_department_file($company_id, $file_id))
			redirect('departments');
		
		// Get hash name.
		$hash_name = $this->Departments_model->get_hash_name($company_id, $file_id);
	
		if(!$hash_name)
		{
			$data['error'] = 'There was an error processing.';
			$this->session->set_flashdata($data);
				
			redirect("departments/view/{$department_id}");
		}
	
		// Remove file from database.
		if(!$this->Departments_model->remove_file($company_id, $file_id))
		{
			$data['error'] = 'There was an error processing.';
			$this->session->set_flashdata($data);
	
			redirect("departments/view/{$department_id}");
		}
	
		// Delete the file from server.
		unlink(getcwd().DIRECTORY_SEPARATOR.'assets'.DIRECTORY_SEPARATOR.'uploads'.DIRECTORY_SEPARATOR.'departments'.DIRECTORY_SEPARATOR.$hash_name[0]['departments_files_hash_name']);
	
		redirect("departments/view/{$department_id}");
	}
	
	/*
	 * Update a department with new information. You must have the
	 * correct access level in order to do this.
	 * 
	 * @department_id The department we are going to update.
	 */
	function update($department_id = null)
	{
		// Verify they are admin.
		if(!$this->session->userdata('level'))
		{
			$data['error'] = 'You do not have admin access to update an asset.';
			$this->session->set_flashdata($data);
			
			redirect('departments');
		}
		
		// Verify they have typed in a department.
		if(!$department_id)
			redirect('departments');
		
		$company_id = 1;
		$user_id    = $this->session->userdata('user_id');
		
		// Verify the department belongs to the company.
		if(!$this->Company_model->is_valid_department($company_id, $department_id))
			redirect('departments');
		
		if(!$_POST['name'])
		{
			$data['error'] = 'Please fill out a name.';
			$this->session->set_flashdata($data);
				
			redirect("departments/view/{$department_id}");
		}
		
		// Get all of the POST data and filter what needs filtered.
		$name 	          = $this->db->escape($_POST['name']);
		$current_assigned = $this->Departments_model->get_users($company_id, $department_id);
		$current_projects = $this->Departments_model->get_department_projects($company_id, $department_id);
		$description      = $this->db->escape($_POST['description']);
		
		// Check to see if any data is coming in.
		if(isset($_POST['projects']))
			$new_projects = array_values(array_unique($_POST['projects']));
		else
			$new_projects = false;
		
		if(isset($_POST['assigned']))
			$new_assigned = array_values(array_unique($_POST['assigned']));
		else
			$new_assigned = false;
		
		// Update basic information about the department.
		if(!$this->Departments_model->update_information($company_id, $department_id, $name, $description))
		{
			$data['error'] = 'There was an error processing.';
			$this->session->set_flashdata($data);
			
			redirect("departments/view/{$department_id}");
		}
		
		// Update the currently assigned users to the default.
		if($current_assigned)
		{
			for($i = 0; $i < count($current_assigned); ++$i)
			{
				if(!$this->Company_model->assign_default_department_to_user($company_id, $current_assigned[$i]['user_id']))
				{
					$data['error'] = 'There was an error processing.';
					$this->session->set_flashdata($data);
						
					redirect("departments/view/{$department_id}");
				}
			}
		}
		
		// Update the new users to the current project.
		if($new_assigned)
		{
			for($i = 0; $i < count($new_assigned); ++$i)
			{
				// Verify the user belongs to the company.
				if(!$this->Company_model->is_valid_user($company_id, $new_assigned[$i]))
				{
					redirect('departments');
				}
				
				if(!$this->Departments_model->update_assigned($company_id, $department_id, $new_assigned[$i]))
				{
					$data['error'] = 'There was an error processing.';
					$this->session->set_flashdata($data);
						
					redirect("departments/view/{$department_id}");
				}
			}
		}
		
		// Remove all of the projects assigned to the department.
		if($current_projects)
		{
			for($i = 0; $i < count($current_projects); ++$i)
			{
				if(!$this->Company_model->assign_default_department_to_project($company_id, $current_projects[$i]['project_id']))
				{
					$data['error'] = 'There was an error processing.';
					$this->session->set_flashdata($data);
				
					redirect("departments/view/{$department_id}");
				}
			}
		}
		
		// Re-assign the new projects to the department.
		if($new_projects)
		{
			for($i = 0; $i < count($new_projects); ++$i)
			{
				// Verify the project belongs to the company.
				if(!$this->Company_model->is_valid_project($company_id, $new_projects[$i]))
				{
					redirect('departments');
				}
					
				if(!$this->Departments_model->update_projects($company_id, $department_id, $new_projects[$i]))
				{
					$data['error'] = 'There was an error processing.';
					$this->session->set_flashdata($data);
						
					redirect("departments/view/{$department_id}");
				}
			}
		}
		
		redirect("departments/view/{$department_id}");
	}
	
	/*
	 * Creating a new department. You must have the
	 * correct access level in order to do this.
	 */
	function create()
	{
		$message = '';
		$company_id    	  = 1;
		$company_users    = $this->company_model->get_all_users_include_inactive($company_id);
		$company_projects = $this->company_model->get_all_projects_include_inactive($company_id);
		
		$data = array('company_users'    => $company_users,
					  'company_projects' => $company_projects,
					  'message' => $message);
		
		// Load views.
		$this->data['ptitle'] = 'Create Department';
		$this->session->set_userdata('page', 12);
		$this->tmadmin->tmView('departments/create', $data);
	}
	
	/*
	 * Insert a new project. You must have the
	 * correct access level in order to do this.
	 */
	function insert()
	{
		// Get backfill information in case of bad input.
		$data['backfill_description'] = $_POST['description'];
		
		if(!$_POST['name'])
		{
			$data['error'] = 'Please fill out a name.';
			$this->session->set_flashdata($data);
		
			redirect("departments/create");
		}
		
		$company_id    = 1;
		$user_id       = $this->session->userdata('user_id');
		$name 	       = $this->db->escape($_POST['name']);
		$description   = $this->db->escape($_POST['description']);
		$department_id = $this->Departments_model->insert_department($company_id, $name, $description);
		
		if(!$department_id)
		{
			$data['error'] = 'Please fill out all of the fields.';
			$this->session->set_flashdata($data);
		
			redirect("departments/create");
		}
		
		// Check to see if any data is coming in.
		if(isset($_POST['projects']))
			$new_projects = array_values(array_unique($_POST['projects']));
		else
			$new_projects = false;
		
		if(isset($_POST['assigned']))
			$new_assigned = array_values(array_unique($_POST['assigned']));
		else
			$new_assigned = false;
		
		// Update the new users to the current project.
		if($new_assigned)
		{
			for($i = 0; $i < count($new_assigned); ++$i)
			{
				// Verify the user belongs to the company.
				if(!$this->company_model->is_valid_user($company_id, $new_assigned[$i]))
				{
					$data['error'] = 'There was an error processing.';
					$this->session->set_flashdata($data);
		
					redirect("departments/view/{$department_id}");
				}
		
				if(!$this->Departments_model->update_assigned($company_id, $department_id, $new_assigned[$i]))
				{
					$data['error'] = 'There was an error processing.';
					$this->session->set_flashdata($data);
		
					redirect("departments/view/{$department_id}");
				}
			}
		}
		
		// Re-assign the new projects to the department.
		if($new_projects)
		{
			for($i = 0; $i < count($new_projects); ++$i)
			{
				// Verify the project belongs to the company.
				if(!$this->company_model->is_valid_project($company_id, $new_projects[$i]))
				{
					$data['error'] = 'There was an error processing.';
					$this->session->set_flashdata($data);
		
					redirect("departments/view/{$department_id}");
				}
					
				if(!$this->Departments_model->update_projects($company_id, $department_id, $new_projects[$i]))
				{
					$data['error'] = 'There was an error processing.';
					$this->session->set_flashdata($data);
		
					redirect("departments/view/{$department_id}");
				}
			}
		}
	
		redirect("departments/view/{$department_id}");
	}
	
	/*
	 * Deactivate a department. You must have the
	 * correct access level in order to do this.
	 * 
	 * @department_id The department that is going to be deactivated.
	 */
	function deactivate($department_id = null)
	{
		// Verify they are admin.
		if(!$this->session->userdata('level'))
		{
			$data['error'] = 'You do not have admin access to deactivate an asset.';
			$this->session->set_flashdata($data);
		
			redirect('departments');
		}
	
		// Verify they have typed in a department.
		if(!$department_id)
			redirect('departments');
	
		$company_id = 1;
		$user_id    = $this->session->userdata('user_id');
		
		// Verify the department belongs to the company.
		if(!$this->company_model->is_valid_department($company_id, $department_id))
			redirect("departments");
		
		// Verify it is not default.
		if($this->company_model->is_default_department($company_id, $department_id))
		{
			$data['error'] = 'You cannot deactivate a default department.';
			$this->session->set_flashdata($data);
		
			redirect("departments/view/{$department_id}");
		}
	
		// Try to deactivate the department.
		if(!$this->Departments_model->deactivate($company_id, $department_id))
		{
			$data['error'] = 'There was an error processing.';
			$this->session->set_flashdata($data);
	
			redirect("departments/view/{$department_id}");
		}
	
		redirect("departments/view/{$department_id}");
	}
	
	/*
	 * Activate a department. You must have the
	 * correct access level in order to do this.
	 * 
	 * @department_id The department that is going to be activated.
	 */
	function activate($department_id = null)
	{
		// Verify they are admin.
		if(!$this->session->userdata('level'))
		{
			$data['error'] = 'You do not have admin access to activate an asset.';
			$this->session->set_flashdata($data);
		
			redirect('departments');
		}
	
		// Verify they have typed in a department.
		if(!$department_id)
			redirect('departments');
	
		$company_id = 1;
	
		// Verify the department belongs to the company.
		if(!$this->company_model->is_valid_department($company_id, $department_id))
			redirect("departments");
	
		// Try to activate the department.
		if(!$this->Departments_model->activate($company_id, $department_id))
		{
			$data['error'] = 'There was an error processing.';
			$this->session->set_flashdata($data);
	
			redirect("departments/view/{$department_id}");
		}
	
		redirect("departments/view/{$department_id}");
	}
	
	/*
	 * Delete a department. You must have the
	 * correct access level in order to do this.
	 * 
	 * @department_id The department that is going to be deleted.
	 */
	function delete($department_id = null)
	{
		// Verify they are admin.
		if(!$this->session->userdata('level'))
		{
			$data['error'] = 'You do not have admin access to delete an asset.';
			$this->session->set_flashdata($data);
		
			redirect('departments');
		}
		
		// Verify they have typed in a department.
		if(!$department_id)
			redirect('departments');
		
		$company_id = 1;
		$user_id    = $this->session->userdata('user_id');
		
		// Verify the department belongs to the company.
		if(!$this->Company_model->is_valid_department($company_id, $department_id))
			redirect("departments");
		
		// Verify it is not default.
		if($this->Company_model->is_default_department($company_id, $department_id))
		{
			$data['error'] = 'You cannot delete a default department.';
			$this->session->set_flashdata($data);
		
			redirect("departments/view/{$department_id}");
		}
		
		if(!$this->Departments_model->delete_department($company_id, $department_id))
		{
			$data['error'] = 'Error deleting department.';
			$this->session->set_flashdata($data);
			
			redirect("departments/view/{$department_id}");
		}
		
		redirect("departments");
	}
	
	/*
	 * Creating a comment on a file. The user must input
	 * the comment field in order to process.
	 *
	 * @department_id The department that is getting the files comment.
	 * @file_id       The file that is getting the comment.
	 */
	function comment($department_id = null, $file_id = null)
	{
		$company_id = 1;
		$user_id    = $this->session->userdata('user_id');
	
		// Verify the department belongs to the company.
		if(!$this->Company_model->is_valid_department($company_id, $department_id))
			redirect('departments');
	
		// Verify the file belongs to the company.
		if(!$this->Company_model->is_valid_department_file($company_id, $file_id))
			redirect('departments');
	
		// Verify they typed in a comment.
		if(!$_POST['comment'])
		{
			$data['error'] = 'Please fill out the comments field.';
			$this->session->set_flashdata($data);
	
			redirect("departments/view/{$department_id}");
		}
	
		$comment = $this->db->escape($_POST['comment']);
		
		// Comment on the departments file.
		if(!$this->Departments_model->comment_on_file($company_id, $department_id, $file_id, $user_id, $comment))
		{
			$data['error'] = 'There was an error commenting on the tickets file.';
			$this->session->set_flashdata($data);
	
			redirect("departments/view/{$department_id}");
		}
	
		redirect("departments/view/{$department_id}");
	}
}